
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PayPanel.java
 *
 * Created on Apr 11, 2010, 3:07:08 PM
 */

/**
 *This class displays the pay window for the customer so that they can pay
 * @author Steven
 */

package edu.asu.cse360.client.ui.frame;


import edu.asu.cse360.client.context.RestaurantContext;
import edu.asu.cse360.client.util.CustomerConfiguration;
import edu.asu.cse360.context.ServiceFactory;
import edu.asu.cse360.model.ItemOrder;
import edu.asu.cse360.model.MenuItem;
import edu.asu.cse360.model.Order;
import edu.asu.cse360.model.PaymentConfirmation;
import edu.asu.cse360.model.PaymentType;
import edu.asu.cse360.model.Receipt;
import edu.asu.cse360.model.Table;
import edu.asu.cse360.model.TableStatus;
import edu.asu.cse360.service.ItemOrderService;
import edu.asu.cse360.service.MenuItemService;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.AbstractListModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.ListModel;





public class PayPanel extends javax.swing.JPanel {

    private static PayPanel instance;
    public static PayPanel instance(CustomerConfiguration config) {
        if(instance == null){
            instance = new PayPanel(config);
        }
        return instance;
    }

    private ItemOrderModel orderItems;
    private Order order;
    private ItemOrderService orderItemSvc;
    private double tipRate;
    private double totalTax;
    private double totalPrice;
    private int groupTotal;
    private int currentGroup;
    private double taxRate;
    private int ratingItem;
    private boolean rated = false;
    //private List<ItemOrder> itemOrders;
    int[] number;
    private List<Receipt> receipts;
    private DefaultComboBoxModel paymentModel;
    private int count;
    private CustomerConfiguration customerConfiguration;


    
    /** Creates new form PayPanel */
    public PayPanel(CustomerConfiguration customerConfiguration) {
        this.customerConfiguration = customerConfiguration;
        count = 0;
        orderItemSvc = ServiceFactory.getItemOrderService();
        orderItems = new ItemOrderModel();
        paymentModel = new DefaultComboBoxModel(PaymentType.values());
        initComponents();
        pnlRate.setVisible(false);
        totalPrice = 0.0;
        tipRate = 0.0;
        currentGroup = 1;
        groupTotal = 1;
        receipts = new ArrayList();
        String total = NumberFormat.getCurrencyInstance().format(totalPrice);
        String tax = NumberFormat.getCurrencyInstance().format(taxRate);
        lblTax.setText(tax);
        lblTotal.setText(total);

    }

    public void removeOrder(ItemOrder removable)
    {
        order.removeItemOrder(removable);
        listOrder.updateUI();
        recalculate(order);
    }

    public void reset(){
        count = 0;
        totalPrice = 0;
    }
    public void recalculate(Order order){
        this.order = order;
        count = 0;
        totalPrice = 0;
        orderItems.setItemOrders(order.getItemOrders());
        for(ItemOrder itemOrder: this.order.getItemOrders()){

            totalPrice += itemOrder.getMenuItem().getPrice();
        }
        taxRate = .08 * totalPrice;
        totalPrice += tipRate;
        totalPrice += taxRate;
        totalTax = totalPrice;
        String total = NumberFormat.getCurrencyInstance().format(totalPrice);
        String tax = NumberFormat.getCurrencyInstance().format(taxRate);
        lblTax.setText(tax);
        lblTotal.setText(total);
        listOrder.updateUI();
        lblTax.updateUI();
        lblTotal.updateUI();
        this.updateUI();
    }

   public void setOrder(Order order){
        this.order = order;
        count = 0;
        orderItems.setItemOrders(order.getItemOrders());
        for(ItemOrder itemOrder: this.order.getItemOrders()){

            totalPrice += itemOrder.getMenuItem().getPrice();
        }
        taxRate = .08 * totalPrice;
        totalPrice += tipRate;
        totalPrice += taxRate;
        totalTax = totalPrice;
        String total = NumberFormat.getCurrencyInstance().format(totalPrice);
        String tax = NumberFormat.getCurrencyInstance().format(taxRate);
        lblTax.setText(tax);
        lblTotal.setText(total);
        listOrder.updateUI();
        lblTax.updateUI();
        lblTotal.updateUI();
        this.updateUI();
        number = new int [orderItems.getSize()];
        for(int i = 0; i < orderItems.getSize(); i++){
            number[i] = 0;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listOrder = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblTotal = new javax.swing.JLabel();
        btnPay = new javax.swing.JButton();
        tip = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        lblTax = new javax.swing.JLabel();
        txtTip = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        comboPayment = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        boxSplit = new javax.swing.JComboBox();
        btnSplit = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        txtGroup = new javax.swing.JLabel();
        pnlRate = new javax.swing.JPanel();
        boxRate = new javax.swing.JComboBox();
        btnRate = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        lblRating = new javax.swing.JLabel();

        listOrder.setModel(getOrderItemModel());
        listOrder.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listOrderValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listOrder);

        jLabel1.setText("Your Order");

        jLabel3.setText("Total");

        lblTotal.setText(" ");

        btnPay.setText("Pay Now");
        btnPay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPayActionPerformed(evt);
            }
        });

        tip.setText("Tip");

        jLabel7.setText("Tax");

        txtTip.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtTipKeyPressed(evt);
            }
        });

        jLabel4.setText("Payment Method");

        comboPayment.setModel(paymentModel);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE)
                .addGap(150, 150, 150))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnPay)
                .addContainerGap(359, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tip)
                .addGap(18, 18, 18)
                .addComponent(txtTip, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(358, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblTax, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(28, 28, 28)
                                .addComponent(lblTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(comboPayment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel4))))
                .addContainerGap(208, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel7)
                            .addComponent(lblTax, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 211, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(tip)
                            .addComponent(txtTip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(comboPayment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lblTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnPay)
                .addContainerGap())
        );

        boxSplit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }));

        btnSplit.setText("Split");
        btnSplit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSplitActionPerformed(evt);
            }
        });

        jLabel2.setText("# of ways to Split Check");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(txtGroup, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(43, 43, 43)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnSplit)
                            .addComponent(boxSplit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(100, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(boxSplit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addComponent(btnSplit)
                .addGap(18, 18, 18)
                .addComponent(txtGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(129, Short.MAX_VALUE))
        );

        boxRate.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));

        btnRate.setLabel("Rate");
        btnRate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRateActionPerformed(evt);
            }
        });

        jLabel5.setText("Order Rating");

        javax.swing.GroupLayout pnlRateLayout = new javax.swing.GroupLayout(pnlRate);
        pnlRate.setLayout(pnlRateLayout);
        pnlRateLayout.setHorizontalGroup(
            pnlRateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlRateLayout.createSequentialGroup()
                .addGroup(pnlRateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlRateLayout.createSequentialGroup()
                        .addGap(103, 103, 103)
                        .addComponent(btnRate))
                    .addGroup(pnlRateLayout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addComponent(jLabel5)
                        .addGap(18, 18, 18)
                        .addComponent(boxRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlRateLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblRating, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(431, Short.MAX_VALUE))
        );
        pnlRateLayout.setVerticalGroup(
            pnlRateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlRateLayout.createSequentialGroup()
                .addGap(112, 112, 112)
                .addGroup(pnlRateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(boxRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addComponent(btnRate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                .addComponent(lblRating, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pnlRate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pnlRate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void boxRateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boxRateActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_boxRateActionPerformed

    private void listOrderValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listOrderValueChanged
        pnlRate.setVisible(true);
        ratingItem = listOrder.getSelectedIndex() + 1;
        lblRating.setText("");

    }//GEN-LAST:event_listOrderValueChanged

    private void btnSplitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSplitActionPerformed
        int split = (Integer) boxSplit.getSelectedIndex() + 1;
        double splitTotal = totalPrice/split;
        String total = NumberFormat.getCurrencyInstance().format(splitTotal);
        lblTotal.setText(total);
        groupTotal = split;
        txtGroup.setText("Group # 1 is now paying");
        /*for(int i=1; i<=split; i++)
        {
            Receipt custReceipt = new Receipt(this.order, RestaurantContext.getTable());
            receipts.add(custReceipt);
        }*/
    }//GEN-LAST:event_btnSplitActionPerformed

    private void txtTipKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTipKeyPressed
        if(isDouble(txtTip.getText()))
        {
            if(txtTip.getText() != null && Double.valueOf(txtTip.getText()) != null) {
                if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER){
                    totalTax = totalPrice;
                    totalTax = totalTax/groupTotal;
                    tipRate = Double.valueOf(txtTip.getText());
                    totalTax += tipRate;
                    String total = NumberFormat.getCurrencyInstance().format(totalTax);
                    lblTotal.setText(total);
                }
            }
        }
    }//GEN-LAST:event_txtTipKeyPressed

    private void btnPayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPayActionPerformed
        int optionChosen = 999;
        String cardNumber = "";
        if(groupTotal==currentGroup)
        {
            Receipt custReceipt = new Receipt(this.order, RestaurantContext.getTable());
            receipts.add(custReceipt);
            custReceipt.setTotal(totalTax);
            custReceipt.setTip(tipRate);
            custReceipt.setTax(taxRate);
   
            if(comboPayment.getSelectedItem().equals(PaymentType.CASH))
            {
                optionChosen = JOptionPane.showConfirmDialog(null, "Please insert cash payment now.","Payment", JOptionPane.OK_OPTION);
            }else if(comboPayment.getSelectedItem().equals(PaymentType.CREDIT))
            {
                cardNumber = JOptionPane.showInputDialog(null, "Please enter your card  number", "Payment", JOptionPane.OK_OPTION);
            }else if(comboPayment.getSelectedItem().equals(PaymentType.DEBIT))
            {
                cardNumber = JOptionPane.showInputDialog(null, "Please enter your card  number", "Payment", JOptionPane.OK_OPTION);
            }
            if(optionChosen == JOptionPane.OK_OPTION || !cardNumber.equals("")){
            orderCompleted();
            customerConfiguration.configure(AppFrame.getAppFrame());
            }
        }else{
            if(comboPayment.getSelectedItem().equals(PaymentType.CASH))
             {
                 optionChosen = JOptionPane.showConfirmDialog(null, "Please insert cash payment now.","Payment", JOptionPane.OK_OPTION);
             }else if(comboPayment.getSelectedItem().equals(PaymentType.CREDIT))
             {
                 cardNumber = JOptionPane.showInputDialog(null, "Please enter your Credit card  number", "Payment", JOptionPane.OK_OPTION);
             }else if(comboPayment.getSelectedItem().equals(PaymentType.DEBIT))
             {
                 cardNumber = JOptionPane.showInputDialog(null, "Please enter your Debit card  number", "Payment", JOptionPane.OK_OPTION);
             }
        }
        if(optionChosen == JOptionPane.OK_OPTION || !cardNumber.equals(""))
        {
             currentGroup++;
             txtGroup.setText("Group # " + Integer.toString(currentGroup) + " is now paying");
             totalTax = totalPrice;
             totalTax = totalTax/groupTotal;
             if(txtTip.getText().isEmpty() == false){
                tipRate = Double.valueOf(txtTip.getText());
             }else{
                 tipRate = 0.0;
             }
             String total = NumberFormat.getCurrencyInstance().format(totalTax);
             lblTotal.setText(total);
             txtTip.setText("");
             Receipt custReceipt = new Receipt(this.order, RestaurantContext.getTable());
             receipts.add(custReceipt);
             custReceipt.setTotal(totalTax);
             custReceipt.setTip(tipRate);
             custReceipt.setTax(taxRate);
             count++;
             
        Random generator = new Random();
        String confirmNum = "";
        for(int i=0; i<=4; i++)
        {
            confirmNum += generator.nextInt(9);
        }
        PaymentConfirmation confirmation = new PaymentConfirmation();
        confirmation.setConfirmationKey(confirmNum);
        ServiceFactory.getOrderService().saveConfirmation(confirmation);
        JOptionPane.showMessageDialog(null, "Your confirmation number is: " + confirmNum);
        }
        else
            JOptionPane.showMessageDialog(null, "Invalid payment, please pay again");
    }//GEN-LAST:event_btnPayActionPerformed

    public void orderCompleted()
    {
        count = 0;
        pnlRate.setVisible(false);
        totalPrice = 0.0;
        tipRate = 0.0;
        currentGroup = 1;
        groupTotal = 1;
        taxRate = 0;
        receipts = new ArrayList();
        String total = NumberFormat.getCurrencyInstance().format(totalPrice);
        String tax = NumberFormat.getCurrencyInstance().format(taxRate);
        lblTax.setText(tax);
        lblTotal.setText(total);
        lblTax.updateUI();
        lblTotal.updateUI();
        Table table = RestaurantContext.getTable();
        table.setStatus(TableStatus.DIRTY);
        ServiceFactory.getTableService().save(table);
    }

    private void btnRateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRateActionPerformed
       
        if(number[ratingItem-1] == 0)
        {
            int usersRating = (Integer) boxRate.getSelectedIndex() + 1;
            int selectedIndex = listOrder.getSelectedIndex();
            ItemOrder selectedOrder = orderItems.getOrderItemAt(selectedIndex);
            MenuItem selectedMenuItem = selectedOrder.getMenuItem();
            MenuItemService itemSvc = ServiceFactory.getMenuItemService();
            Double currentRating = selectedMenuItem.getRating();
            double newRating;
            double frequency = selectedMenuItem.getRatingFrequency();
            if(currentRating == null){
                newRating = usersRating;
            }else{
                newRating = currentRating * frequency;
                newRating += usersRating;
                newRating = newRating/(frequency + 1);
            }
            selectedMenuItem.setRating(newRating);
            selectedMenuItem.setRatingFrequency(frequency + 1);
            itemSvc.save(selectedMenuItem);
            newRating = (int) Math.rint(selectedMenuItem.getRating());
            lblRating.setText(Double.toString(newRating));
            number[ratingItem-1] = 1;
           // btnRate.setEnabled(false);
        }
        else
            lblRating.setText("You have already rated this Item");

    }//GEN-LAST:event_btnRateActionPerformed

    public boolean isDouble(String text)
    {
        try
        {
            Double.valueOf(text);
                return true;
        }
        catch(Exception e)
        {
                return false;
        }
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox boxRate;
    private javax.swing.JComboBox boxSplit;
    private javax.swing.JButton btnPay;
    private javax.swing.JButton btnRate;
    private javax.swing.JButton btnSplit;
    private javax.swing.JComboBox comboPayment;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblRating;
    private javax.swing.JLabel lblTax;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JList listOrder;
    private javax.swing.JPanel pnlRate;
    private javax.swing.JLabel tip;
    private javax.swing.JLabel txtGroup;
    private javax.swing.JTextField txtTip;
    // End of variables declaration//GEN-END:variables

        private ListModel getOrderItemModel(){
         return orderItems;
    }
    private class ItemOrderModel extends AbstractListModel{

      private List<ItemOrder> orderItems;

      public ItemOrderModel(List<ItemOrder> newOrders)
      {
            orderItems = new ArrayList<ItemOrder>();
            if(newOrders != null){
                orderItems.addAll(newOrders);
            }
      }

        private ItemOrderModel() {
            this(null);
        }

        //Override the methods in the abstract class.
      public int getSize()
      { return orderItems.size(); }

      public List<ItemOrder> getItemOrders()
      {
          return orderItems;
      }

      public Object getElementAt(int index)
      { return orderItems.get(index).getMenuItem().getName(); }

      public void addItem(ItemOrder item)
      {
          orderItems.add(item);
      }
      public void removeItem(ItemOrder item)
      {
          orderItems.remove(item);
      }

      public ItemOrder getOrderItemAt(int index)
      {
          return orderItems.get(index);
      }

        private void setItemOrders(List<ItemOrder> itemOrders) {
           this.orderItems = itemOrders;
           listOrder.updateUI();
        }
    }

    /*
      private Order createMockOrder(){
         ItemOrderService itemSvc = ServiceFactory.getItemOrderService();
         Order mockOrder = new Order();
         itemOrders = new ArrayList<ItemOrder>();
         itemOrders.add(itemSvc.find(1));
         itemOrders.add(itemSvc.find(2));
         itemOrders.add(itemSvc.find(3));
         itemOrders.add(itemSvc.find(4));
         itemOrders.add(itemSvc.find(5));
         mockOrder.setItemOrders(itemOrders);
         return mockOrder;
    }
*/

 }
 
 
